import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import bcrypt from 'bcrypt';

export async function POST(req: NextRequest) {
  try {
    const { username, password } = await req.json();

    if (!username || !password) {
      return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
    }

    const existing = await prisma.user.findUnique({ where: { username } });
    if (existing) {
      return NextResponse.json({ error: '用户名已经存在' }, { status: 409 });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const user = await prisma.user.create({
      data: { username, password: hashedPassword },
    });

    const res = NextResponse.json(
      { message: '注册成功', user: { id: user.id, username: user.username } },
      { status: 200 }
    );

    res.cookies.set('x-user-id', user.id, {
      httpOnly: true,
      path: '/',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7, // 7天
    });

    return res;
  } catch (err: any) {
    console.error('[注册错误]', err);
    return NextResponse.json({ error: '服务器内部错误' }, { status: 500 });
  }
}
